<template>
  <div>
    <van-row type="flex" justify="center" style="margin-top:80px" v-if="loading">
      <van-loading type="spinner" size="24px">加载中...</van-loading>
    </van-row>
    <van-cell title="作业名称" :value="show.taskName" />
    <van-cell title="任务 ID">{{taskId}}</van-cell>
    <van-cell title="类型" value="电务作业" />
    <van-cell title="状态">
      <van-tag v-if="this.taskInfo.state === 1">待审核</van-tag>
      <van-tag type="warning" v-else-if="this.taskInfo.state === 2">审核中</van-tag>
      <van-tag type="primary" v-else-if="this.taskInfo.state === 3">已批准</van-tag>
      <van-tag type="danger" v-else-if="this.taskInfo.state === 4">已拒绝</van-tag>
      <van-tag type="success" v-else-if="this.taskInfo.state === 5">进行中</van-tag>
      <van-tag type="warning" v-else-if="this.taskInfo.state === 6 && taskSetting.haveEvacuateState">撤离中</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 6 && !taskSetting.haveEvacuateState">已完成</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 7">已销毁</van-tag>
      <van-tag v-else-if="this.taskInfo.state === 8">已终止</van-tag>
      <van-tag v-else>未知</van-tag>
    </van-cell>
    <van-cell
      title="操作"
      v-if="this.taskInfo.state === 3 || this.taskInfo.state === 5 || this.taskInfo.state === 6"
    >
      <span v-if="this.taskInfo.state === 3">
        <van-tag
          v-if="!(permission.operate!=1 && (!permission.operate || !permission.operate.start))"
          type="success"
          @click="onClickStartTask"
        >开始作业</van-tag>
      </span>
      <span v-else-if="this.taskInfo.state === 5">
        <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
        <van-tag
          v-if="!(permission.operate!=1 && (!permission.operate || !permission.operate.end))"
          type="danger"
          @click="onClickEndTask"
        >结束作业</van-tag>
      </span>
      <span v-else-if="this.taskSetting.haveEvacuateState && this.taskInfo.state === 6">
        <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
        <van-tag
          v-if="!(permission.operate!=1 && (!permission.operate || !permission.operate.terminate))"
          type="danger"
          @click="onClickTerminateTask"
        >终止作业</van-tag>
      </span>
    </van-cell>
    <van-cell
      title="人工预警"
      v-if="taskSetting.hasManualWarn && (this.taskInfo.state === 6 || this.taskInfo.state === 5 || this.taskInfo.curManualWarnId)"
    >
      <span
        v-if="!this.taskInfo.curManualWarnId && !(!permission.operate || !permission.operate.manualWarn)"
      >
        <van-tag type="success" @click="SetManualWarn = true">开始预警</van-tag>
      </span>
      <span
        v-else-if="this.taskInfo.curManualWarnId && !(!permission.operate || !permission.operate.manualWarn)"
      >
        <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
        <van-tag type="danger" @click="onClickEndManualWarn">结束预警</van-tag>
      </span>
      <span v-else-if="this.taskInfo.curManualWarnId">
        <!-- <van-tag type="warning" style="margin-right:32px">人工预警</van-tag> -->
        <span>有预警</span>
      </span>
      <span v-else>
        <span>无预警</span>
      </span>
    </van-cell>
    <!-- <van-cell title="创建人" value="张三" />
    <van-cell title="创建时间" value="2022-07-25 09:06:31" />-->
    <van-cell title="计划时间" :value="show.planedTime" />
    <van-cell title="开始时间" :value="show.beginTime" />
    <van-cell title="结束时间" :value="show.endTime" />
    <van-cell v-if="taskSetting.haveEvacuateState" title="终止时间" :value="show.terminateTime" />
    <van-cell v-if="taskSetting.autoTimeControl" title="预计开始" :value="show.beginTime_order" />
    <van-cell v-if="taskSetting.autoTimeControl" title="预计结束" :value="show.terminateTime_order" />
    <van-cell v-if="taskSetting.autoTimeControl" title="自动开始" :value="show.autoBegin" />
    <van-cell v-if="taskSetting.autoTimeControl" title="自动结束" :value="show.autoEnd" />
    <van-cell v-if="taskSetting.setStation" title="所属车站" :value="show.stationName" />
    <van-cell v-if="taskSetting.hasWorkArea" title="作业地点" :value="show.workPlace" />
    <van-cell v-if="!taskSetting.hasWorkArea" title="作业地点" :value="show.areaComment" />
    <van-cell title="作业范围" :value="show.workRange" />
    <van-cell v-if="taskSetting.hasWorkArea" title="范围补充" :value="show.areaComment" />
    <van-cell title="作业内容" :value="show.workContent" />
    <van-cell v-if="taskSetting.hasFence" title="作业区域" :value="show.fence" @click="onClickFence" />
    <van-cell title="我的角色" :value="show.role" />
    <van-cell v-if="taskSetting.haveWorkLeader" title="作业组长" :value="show.workLeader" @click="onClickRole('workLeader')" />
    <van-cell :title="taskSetting.showInformation.managerShowName" :value="show.manager" @click="onClickRole('manager')" />
    <van-cell title="联络员" :value="show.liaison" @click="onClickRole('liaison')" />
    <van-cell title="安全员" :value="show.safeman" @click="onClickRole('safeman')" />
    <van-cell title="作业人员" :value="show.worker" @click="onClickRole('worker')" />
    <van-cell title="备注" :value="taskInfo.comment" />
    <van-cell
      title="修改"
      v-if="(this.taskInfo.state === 3 || (taskSetting.autoTimeControl && (this.taskInfo.state === 5 || this.taskInfo.state === 6))) && (permission.update)"
    >
      <span v-if="this.taskInfo.state === 3 && (permission.update)">
        <van-tag type="success" @click="onClickUpdateTask">修改任务</van-tag>
      </span>
      <span
        v-else-if="taskSetting.autoTimeControl && (this.taskInfo.state === 5 || this.taskInfo.state === 6) && (permission.update)"
      >
        <van-tag type="success" @click="onClickUpdateTask">修改时间</van-tag>
      </span>
    </van-cell>
    <van-cell title="照片" />
    <van-uploader v-model="picFileList" multiple :after-read="afterRead" :deletable="false" />
    <van-dialog v-model="showDetailDialog" :title="dialogTitle">
      <div class="roleDetail">
        <van-cell>
          <van-row>
            <van-col span="4">
              <span class="table-head">ID</span>
            </van-col>
            <van-col span="5">
              <span class="table-head">类型</span>
            </van-col>
            <van-col span="6">
              <span class="table-head">名称</span>
            </van-col>
            <van-col span="9">
              <span class="table-head">组织</span>
            </van-col>
          </van-row>
        </van-cell>
        <van-cell v-for="(item, index) in dialogData" :key="index" @click="onClickDetailItem(item)">
          <van-row>
            <van-col span="4">
              <span class="table-content">{{getRoleDetailID(item)}}</span>
            </van-col>
            <van-col span="5">
              <span class="table-content">{{getRoleDetailType(item)}}</span>
            </van-col>
            <van-col span="6">
              <span class="table-content">{{item.name}}</span>
            </van-col>
            <van-col span="9"></van-col>
          </van-row>
        </van-cell>
      </div>
    </van-dialog>
    <van-popup v-model="SetManualWarn" round position="bottom">
      <van-checkbox-group
        v-model="show.manualWarnType"
        direction="horizontal"
        style="margin-top: 60px; margin-bottom: 30px; icon-size=24px; font-size: 18px; display: flex; justify-content: center; align-items: center;  "
      >
        <van-checkbox name="worker">作业人员</van-checkbox>
        <van-checkbox name="safeman">安全员</van-checkbox>
      </van-checkbox-group>
      <van-field v-model="show.manualWarnContent" type="text" autosize label="预警内容" />
      <div class="submit-area">
        <van-button round style="width:120px;" @click="SetManualWarn = false">取消</van-button>
        <van-button round type="info" style="width:120px;" @click="onClickStartManualWarn">确定</van-button>
      </div>
    </van-popup>
    <van-dialog v-model="showGroupDialog" :title="groupDialogTitle">
      <div class="roleDetail">
        <van-cell title="群组名" :value="groupDialogData.groupName" />
        <van-cell title="简介" :value="groupDialogData.introduction" />
        <div style="height:36px"></div>
        <van-cell>
          <van-row>
            <van-col span="6">
              <span class="table-head">ID</span>
            </van-col>
            <van-col span="9">
              <span class="table-head">名称</span>
            </van-col>
            <van-col span="9">
              <span class="table-head">组织</span>
            </van-col>
          </van-row>
        </van-cell>
        <van-cell v-for="(item, index) in groupDialogData.member" :key="index">
          <van-row>
            <van-col span="6">
              <span class="table-content">{{getRoleDetailID(item)}}</span>
            </van-col>
            <van-col span="9">
              <span class="table-content">{{item.name}}</span>
            </van-col>
            <van-col span="9"></van-col>
          </van-row>
        </van-cell>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// import { getFormatDate, getFormatHourMinute } from '../utils/datetime'
import {
  getPlanTimeStr,
  getBeginEndTimeStr,
  getRoleStr,
  getRoleDetailID,
  getRoleDetailType,
  getTaskInfoRoleShow,
  getWorkPlaceShow,
  getWorkRangeShow,
  fillRoleData,
  getFenceIds,
  getTaskTypeStr,
  getTaskStateStr
} from '../../utils/taskUtils'
import { putTaskOperate, manualWarn } from '@/api/task'
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      loading: true,
      taskId: '',
      SetManualWarn: false,
      baseURL: 'http://152.136.13.167:9527',
      // baseURL: window.location.origin,
      taskInfo: {},
      roleData: {
        workLeader: [],
        manager: [],
        liaison: [],
        safeman: [],
        worker: []
      },
      roleName: {
        workLeader: '作业组长',
        manager: '作业小组长',
        liaison: '联络员',
        safeman: '防护员',
        worker: '作业人员'
      },
      show: {
        role: '',
        manualWarnType: ['worker', 'safeman'],
        manualWarnContent: '',
        planedTime: '---',
        beginTime: '---',
        endTime: '---',
        terminateTime: '---',
        terminateTime_order: '---',
        beginTime_order: '---',
        workLeader: '',
        manager: '',
        liaison: '',
        safeman: '',
        stationName: '',
        worker: '',
        workPlace: '',
        workRange: '',
        fence: '',
        areaComment: '',
        workContent: ''
      },
      showDetailDialog: false,
      dialogTitle: '',
      dialogData: [],
      showGroupDialog: false,
      groupDialogTitle: '',
      groupDialogData: {
        name: '',
        introduction: '',
        member: []
      },
      role: -1,
      picFileList: []
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId', 'permission', 'taskSetting', 'stationIds'])
  },
  watch: {},
  created() {
    this.taskId = this.$router.currentRoute.query.taskId
    this.role = this.$router.currentRoute.query.role
    this.roleName.workLeader = this.taskSetting.showInformation.managerShowName
    try {
      this.getTaskInfo(this.taskId)
      this.$toast('获取任务信息成功')
    } catch (err) {
      // 对异步异常无效，await的异常怎么捕获更合理待研究
      console.log(err)
      this.loading = false
      this.$toast('获取任务信息失败')
    }
    this.getPicURL()
  },
  mounted() {
    this.sockets.subscribe('TaskChangeBriefInfo', async (channelMsg) => {
      console.log('[TASKINFO_DW] Recv Channel TaskChangeBriefInfo')
      if (this.taskId === channelMsg.data.taskId) {
        console.log(channelMsg)
        this.loading = true
        this.getTaskInfo(this.taskId)
        const notice = `当前任务：${getTaskTypeStr(channelMsg.data.type)}(id: ${channelMsg.data.taskId}) ${getTaskStateStr(channelMsg.data.state)}！`
        this.$dialog.alert({
          message: notice
        })
      }
    })
  },
  beforeDestroy() {
    this.sockets.unsubscribe('TaskChangeBriefInfo')
  },
  methods: {
    onClickUpdateTask() {
      const taskCreatePathGW = '/taskupdate/DW'
      const taskInfo = this.taskInfo
      if (this.taskInfo.state === 5) {
        this.$router.push({ path: taskCreatePathGW, query: { taskInfo, taskId: this.taskInfo.taskId, taskState: 5 } })
      } else this.$router.push({ path: taskCreatePathGW, query: { taskInfo, taskId: this.taskInfo.taskId, taskState: 3 } })
    },
    onClickRole(role) {
      this.dialogTitle = this.roleName[role]
      this.dialogData = this.roleData[role]
      this.showDetailDialog = true
    },
    onClickDetailItem(item) {
      if (item.type === 'userGroup' || item.type === 'deviceGroup') {
        this.groupDialogTitle = item.type === 'userGroup' ? `人员组（${item.id}）` : `设备组（${item.id}）`
        this.groupDialogData = item
        this.showGroupDialog = true
      }
    },
    onClickFence() {
      this.$toast('暂不支持查看')
    },
    fillTaskShow(task) {
      this.show.autoBegin = task.autoBegin === 1 ? '是' : '否'
      this.show.autoEnd = task.autoEnd === 1 ? '是' : '否'
      this.show.taskName = task.taskName
      this.show.planedTime = getPlanTimeStr(task.beginTime_plan, task.endTime_plan)
      if (this.taskInfo.beginTime) {
        this.show.beginTime = getBeginEndTimeStr(this.taskInfo.beginTime)
      }
      if (this.taskInfo.beginTime_order) {
        this.show.beginTime_order = getBeginEndTimeStr(this.taskInfo.beginTime_order)
      }
      if (this.taskInfo.terminateTime_order) {
        this.show.terminateTime_order = getBeginEndTimeStr(this.taskInfo.terminateTime_order)
      }
      if (this.taskInfo.endTime) {
        this.show.endTime = getBeginEndTimeStr(this.taskInfo.endTime)
      }
      if (this.taskInfo.terminateTime) {
        this.show.terminateTime = getBeginEndTimeStr(this.taskInfo.terminateTime)
      }
      this.show.role = getRoleStr(parseInt(this.role))
      this.show.workLeader = getTaskInfoRoleShow(this.roleData.workLeader)
      this.show.manager = getTaskInfoRoleShow(this.roleData.manager)
      this.show.liaison = getTaskInfoRoleShow(this.roleData.liaison)
      this.show.safeman = getTaskInfoRoleShow(this.roleData.safeman)
      this.show.worker = getTaskInfoRoleShow(this.roleData.worker)
      this.show.workPlace = getWorkPlaceShow(task.workArea)
      this.show.workRange = getWorkRangeShow(task.workArea.areaKM)
      this.show.fence = task.fenceIds.length ? `作业区域(id:${task.fenceIds.toString()})` : '无'
      const station = task.station
      for (var key in this.stationIds) {
        if (this.stationIds[key].value === station) {
          this.show.stationName = this.stationIds[key].text
        }
      }
      this.show.areaComment = task.workArea.areaComment ? task.workArea.areaComment : ''
      this.show.comment = task.comment ? task.comment : ''
      this.show.workContent = task.workContent
    },
    async getPicURL() {
      const { data } = await this.$http.get('/pic/getImagePaths', { params: { taskId: this.taskId } })
      if (data.code === 0) {
        data.data.forEach((path) => {
          this.picFileList.push({ url: `${window.location.origin}/pic/${path}` })
        })
      }
    },
    async afterRead(e) {
      // 此时可以自行将文件上传至服务器
      e.status = 'uploading'
      e.message = '上传中...'
      const fd = new FormData()
      fd.append('deviceId', this.deviceId)
      if (this.userId) {
        fd.append('userId', this.deviceId)
      }
      fd.append('taskId', this.taskId)
      fd.append('file', e.file)
      await this.$http({
        method: 'post',
        url: '/pic/upload',
        data: fd
      })
      e.status = 'done'
    },
    async getTaskInfo(taskId) {
      const { data } = await this.$http.get('/task/taskInfo', { params: { taskId } })
      if (data.code === 0) {
        this.taskInfo = data.data
        this.taskInfo.fenceIds = getFenceIds(this.taskInfo.fences)
        this.roleData.workLeader = await fillRoleData(this.taskInfo.workLeader)
        this.roleData.manager = await fillRoleData(this.taskInfo.manager)
        this.roleData.liaison = await fillRoleData(this.taskInfo.liaison)
        this.roleData.safeman = await fillRoleData(this.taskInfo.safeman)
        this.roleData.worker = await fillRoleData(this.taskInfo.worker)
        this.fillTaskShow(this.taskInfo)
        this.loading = false
        console.log(this.taskInfo)
      }
    },
    async onClickStartTask() {
      const notice = '此操作将变更任务状态, 是否继续?'
      try {
        const confirmed = await this.$dialog.confirm({
          message: notice,
          confirmButtonText: '确认'
        })

        if (confirmed) { // 通常对话框的 confirm 方法会返回一个解析为布尔值的 Promise
          const respon = await putTaskOperate(this.taskId, 'startTask', {
            userId: this.userId,
            deviceId: this.deviceId
          })

          if (respon.code === 0) {
            this.taskInfo.state = respon.data.state
            this.taskInfo.beginTime = respon.data.beginTime
            if (this.taskInfo.beginTime) {
              this.show.beginTime = getBeginEndTimeStr(this.taskInfo.beginTime)
            }
          }
        }
      } catch (error) {
        // 处理错误，例如显示错误消息
        console.error('处理任务时出错:', error)
      }
    },
    onClickStartManualWarn() {
      const data = {
        taskId: parseInt(this.taskId),
        srcInfo: {
          taskRole: '',
          userId: this.userId,
          deviceInfo: {
            type: 'HT',
            id: this.deviceId
          }
        },
        destRole: this.show.manualWarnType,
        enable: 1,
        content: this.show.manualWarnContent
      }
      manualWarn(data).then((response) => {
        if (response.data.code === 0) {
          this.taskInfo.curManualWarnId = response.data.data.manualWarnId
        }
        this.SetManualWarn = false
      })
    },
    onClickEndManualWarn() {
      const data = {
        taskId: parseInt(this.taskId),
        srcInfo: {
          taskRole: '',
          userId: this.userId,
          deviceInfo: {
            type: 'HT',
            id: this.deviceId
          }
        },
        enable: 0,
        manualWarnId: this.taskInfo.curManualWarnId
      }
      manualWarn(data).then((response) => {
        if (response.data.code === 0) {
          this.taskInfo.curManualWarnId = 0
        }
      })
    },
    async onClickEndTask() {
      const notice = '此操作将变更任务状态, 是否继续?'
      try {
        const confirmed = await this.$dialog.confirm({
          message: notice,
          confirmButtonText: '确认'
        })

        if (confirmed) { // 通常对话框的 confirm 方法会返回一个解析为布尔值的 Promise
          const respon = await putTaskOperate(this.taskId, 'endTask', {
            userId: this.userId,
            deviceId: this.deviceId
          })

          if (respon.code === 0) {
            this.taskInfo.state = respon.data.state
            this.taskInfo.endTime = respon.data.endTime
            if (this.taskInfo.endTime) {
              this.show.endTime = getBeginEndTimeStr(this.taskInfo.endTime)
            }
          }
        }
      } catch (error) {
        // 处理错误，例如显示错误消息
        console.error('处理任务时出错:', error)
      }
    },
    async onClickTerminateTask() {
      const notice = '此操作将变更任务状态, 是否继续?'
      try {
        const confirmed = await this.$dialog.confirm({
          message: notice,
          confirmButtonText: '确认'
        })

        if (confirmed) { // 通常对话框的 confirm 方法会返回一个解析为布尔值的 Promise
          const respon = await putTaskOperate(this.taskId, 'terminateTask', {
            userId: this.userId,
            deviceId: this.deviceId
          })

          if (respon.code === 0) {
            this.taskInfo.state = respon.data.state
            this.taskInfo.terminateTime = respon.data.terminateTime
            if (this.taskInfo.endTime) {
              this.show.terminateTime = getBeginEndTimeStr(this.taskInfo.terminateTime)
            }
          }
        }
      } catch (error) {
        // 处理错误，例如显示错误消息
        console.error('处理任务时出错:', error)
      }
    },
    getRoleDetailID(item) {
      return getRoleDetailID(item)
    },
    getRoleDetailType(item) {
      return getRoleDetailType(item)
    }
  }
}
</script>

<style lang="less" scoped>
.van-cell {
  .van-cell__value {
    min-width: 70%;
  }
}
.submit-area {
  margin: 20px 100px;
  display: flex;
  justify-content: space-between;
}
.roleDetail {
  margin: 20px;
  .table-head {
    font-weight: 700;
    font-size: 30px;
  }
  .table-content {
    font-size: 30px;
  }
  .van-cell {
    padding: 0 20px;
  }
}

.loading {
  margin: 50px;
}
</style>
